package com.mls.fivedistrict.util.http;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * Created by chenxiuxiang on 2018/5/31.
 */
@Slf4j
public class HttpUtil<T> {

    private static HttpUtil httpUtil;

    private HttpUtil() {

    }

    public static HttpUtil getInstance() {
        if (httpUtil == null) {
            httpUtil = new HttpUtil();
        }
        return httpUtil;
    }

    public T get(String url, Class<T> className) {
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<T> response = restTemplate.getForEntity(url, className);
        if (response.getStatusCode().value() == 200) {
            //代表成功
            T body = response.getBody();
            return body;
        } else {
            return null;
        }
    }

    public T post(String url, MultiValueMap params, Class className) {
        try {
            RestTemplate client = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            //  请勿轻易改变此提交方式，大部分的情况下，提交方式都是表单提交
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            //封装参数，千万不要替换为Map与HashMap，否则参数无法传递
            HttpEntity<MultiValueMap<String, String>> request = new HttpEntity(params, headers);//将参数和header组成一个请求
            ResponseEntity<T> response = client.postForEntity(url, request, className);
            if (response.getStatusCode().value() == 200) {
                //代表成功
                T body = response.getBody();
                return body;
            } else {
                return null;
            }
        } catch (Exception e) {
            log.info(e.getMessage());
            return null;
        }

    }

    public T post(String url, HttpHeaders headers, MultiValueMap params, Class<T> className) {
        RestTemplate client = new RestTemplate();
        //封装参数，千万不要替换为Map与HashMap，否则参数无法传递
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity(params, headers);//将参数和header组成一个请求
        ResponseEntity<T> response = client.postForEntity(url, request, className);
        if (response.getStatusCode().value() == 200) {
            //代表成功
            T body = response.getBody();
            return body;
        } else {
            return null;
        }
    }

}
